package com.lh.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.api.dao.DoboCodeMapper;
import com.lh.api.dao.PeriodMapper;
import com.lh.api.dao.UserMapper;
import com.lh.api.service.DoboCodeService;
import com.lh.api.vo.DoboCodeVo;
import com.lh.common.entity.admin.DoboCode;
import com.lh.common.entity.admin.Period;
import com.lh.common.entity.admin.User;
import com.lh.common.enums.UserTypeEnum;
import com.lh.common.utils.HideDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @author Gze
 * @ClassName: ShopServiceImpl
 * @Description: (类作用)
 * @date: 2020-05-14 10:57
 */
@Service
public class DoboCodeServiceImpl extends ServiceImpl<DoboCodeMapper, DoboCode> implements DoboCodeService {
    private static final long BEGINCODE = 10000000;
    private static final Lock LOCK = new ReentrantLock();

    @Autowired
    private PeriodMapper periodMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public int updateByOrderItem(String orderItem, Long periodId, Integer shopNum) {
        String sb = generateDoboCode(periodId,shopNum);

        Map<String, Object> map = new HashMap<>();
        map.put("orderItem",orderItem);
        map.put("periodCode",sb);
        return baseMapper.updateByOrderItem(map);
    }

    @Override
    public List<DoboCodeVo> getDoboCodeList(Period period, List<DoboCodeVo> result) {
        Map<String, DoboCodeVo> doboCodeVoMap = result.stream().collect(Collectors.toMap(DoboCodeVo::getCode, a -> a,(k1, k2)->k1));
        //查询机器人
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", UserTypeEnum.ROBOT);
        List<User> robotList = userMapper.selectList(queryWrapper);
        //如果没有机器人直接返回
        if(CollectionUtils.isEmpty(robotList)){
            return result;
        }
        //确定生成的夺宝码起始位置
        int curNum = 1;
        curNum = period.getCurrenPortion() - 29;
        curNum = curNum < 1 ? 1 : curNum;

        //生成记录
        List<DoboCodeVo> addList = new ArrayList<>();
        for (int i = 0; i < (period.getCurrenPortion() > 30 ? 30 : period.getCurrenPortion()); i++) {
            Long temp = BEGINCODE + curNum ;
            curNum++;
            DoboCodeVo doboCodeVo = doboCodeVoMap.get(temp.toString());
            if(doboCodeVo !=null ){
                continue;
            }
            doboCodeVo = new DoboCodeVo();
            doboCodeVo.setCode(temp.toString());
            User robot =  robotList.get(getNum(0, robotList.size()-1));
            doboCodeVo.setName(robot.getName());
            doboCodeVo.setPhone(HideDataUtil.hidePhoneNo(robot.getPhone()));
            addList.add(doboCodeVo);
        }
        Collections.reverse(addList);
        result.addAll(addList);
        return result;
    }
    public static int getNum(int start,int end) {
        return (int)(Math.random()*(end-start+1)+start);
    }

    /**
     * 生成夺宝码
     * @param periodId  期数ID
     * @param num  购买数量
     * @return
     */
    public  String generateDoboCode(Long periodId, int num){
        LOCK.lock();
        StringBuilder duboCodes = new StringBuilder();
        try {
            Period period = periodMapper.selectById(periodId);
            long curNum = period.getCurrenPortion();//现在人次
            for (int i = 0; i < num ; i++) {
                curNum = curNum +1;
                Long temp = BEGINCODE + curNum ;
                duboCodes.append(temp.toString());
                if(i != num - 1){
                    duboCodes.append(",");
                }
            }
        } catch (Exception e) {
            log.error("Exception:{}", e);
        }finally {
            LOCK.unlock();
        }
        return duboCodes.toString();
    }
}
